package com.ashafa.fileutils;

import java.io.File;
import java.util.TimerTask;

import org.apache.log4j.Logger;

public abstract class DirWatcher extends TimerTask{
	  private static final Logger logger = Logger.getLogger(DirWatcher.class.getName()); 
	  private int numberOfFiles;
	  private File dir;

	  public DirWatcher ( File dir ) throws Exception {
	    if(dir.isDirectory() || !dir.exists())
	    {
	    	this.dir = dir;
	    	this.numberOfFiles = (dir.exists()) ? dir.list().length : 0;
	    } else {
	    	throw new Exception("Directory Watcher: Not a directory!");
	    }
		
	  }

	  public final void run() {
	    int numberOfFiles = (dir.exists()) ? dir.list().length : 0;

	    if( this.numberOfFiles != numberOfFiles ) {
	      this.numberOfFiles = numberOfFiles;
	      try{
	    	  onChange(dir);
	       }catch(Exception e){
	    	   logger.error(e);
	      }
	    }
	  }

	  protected abstract void onChange( File dir ) throws Exception;
	}